package com.example.demo.repo;

import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 库存缓存，用redis hash存储
 * key=common:repo
 * hashKey=商品ID
 * hashValue=库存数
 */
@Repository
public class RepertoryCache {

    private static final String REPO_CACHE_KEY = "common:repo";

    private StringRedisTemplate redisTemplate;

    public RepertoryCache(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private BoundHashOperations<String, String, String> getOperations() {
        return redisTemplate.boundHashOps(REPO_CACHE_KEY);
    }

    // 更新库存
    public void takeOut(Long productId, Integer numbers) {
        getOperations().increment(productId.toString(), -1 * numbers);
    }

    // 获取库存
    public Integer getNumbers(Long productId) {
        String tmp = getOperations().get(productId.toString());
        if (tmp == null) return null;
        else return Integer.valueOf(tmp);
    }

    // 获取所以商品及库存
    public Map<Long, Integer> getRepos() {

        BoundHashOperations<String, String, String> operations = getOperations();

        List<String> productIds = new ArrayList<>(operations.keys());
        List<String> numbers = getOperations().multiGet(productIds);

        Map<Long, Integer> result = new HashMap<>(numbers.size());
        for (int i = 0; i < numbers.size(); i++) {
            result.put(Long.valueOf(productIds.get(i)), Integer.valueOf(numbers.get(i)));
        }

        return result;
    }

    // 初始化库存缓存
    public void initRepo(Map<Long, Integer> repos) {
        Map<String, String> tmp = repos.entrySet().stream()
                .collect(Collectors.toMap(e->e.getKey().toString(), e->e.getValue().toString()));
        getOperations().putAll(tmp);
    }

}
